package sample.akka.demo

import akka.actor.SupervisorStrategy.Stop
import akka.actor._
import java.util.concurrent.TimeUnit

object Dummy extends App {
  val system = ActorSystem("understand")
  val a = system.actorOf(Props[Dummy])

  a ! "Strategy"
  TimeUnit.SECONDS.sleep(1)

  a ! "NewChild"
  TimeUnit.SECONDS.sleep(1)

  a ! "KillChild"
  TimeUnit.SECONDS.sleep(1)

  a ! new RuntimeException()
  TimeUnit.SECONDS.sleep(2)

  a ! "中华人民共和国"
  TimeUnit.SECONDS.sleep(1)

  system.shutdown()
}

class Dummy extends Actor {
  println(s"$this $self initializing ...")

  var child: ActorRef = _

  def receive = {
    case "Strategy" => println(s"strategy: $supervisorStrategy")
    case "NewChild" => child = context.actorOf(Props[Dummy])
    case "KillChild" => child ! new Exception("kill")
    case t: Throwable => throw t
    case a => println("Unhandled: " + a)
  }

  override def supervisorStrategy = OneForOneStrategy() {
    case _: Throwable => Stop
  }

  override def preStart() {
    println(s"$this $self pre start.")
  }

  override def preRestart(reason: Throwable, message: Option[Any]) {
    println(s"$this $self pre restart: $reason, $message")
  }

  override def postRestart(reason: Throwable) {
    println(s"$this $self post restart: $reason")
  }

  override def postStop() {
    println(s"$this $self post stop.")
  }
}
